package com.atguigu.gmall.order.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.cart.client.CartFeignClient;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.model.cart.CartInfo;
import com.atguigu.gmall.model.order.OrderDetail;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.order.service.OrderInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * @Author: 李旭
 * @Time: 14:08
 * @Description: //订单微服务
 * 去结算
 * 提交订单
 */
@RestController
@RequestMapping("/api/order")
public class OrderApiController {


    @Autowired
    private CartFeignClient cartFeignClient;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private OrderInfoService orderInfoService;

    //查询商品清单
    //交易号
    //已经写在了用户微服务中了  本次就不写用户收货地址
    @GetMapping("/trade")
    public Map<String, Object> trade(HttpServletRequest request) {
        Map<String, Object> result = null;
        //1:查询商品清单
        List<CartInfo> cartListChecked = cartFeignClient.getCartListChecked();

        if(!CollectionUtils.isEmpty(cartListChecked)){
            result = new HashMap<>();
            List<OrderDetail> orderDetailList = cartListChecked.stream().map(cartInfo -> {
                OrderDetail detail = new OrderDetail();
                detail.setImgUrl(cartInfo.getImgUrl());
                detail.setSkuName(cartInfo.getSkuName());
                detail.setOrderPrice(cartInfo.getSkuPrice());
                detail.setSkuNum(cartInfo.getSkuNum());
                detail.setSkuId(cartInfo.getSkuId());
                return detail;
            }).collect(Collectors.toList());
            result.put("detailArrayList", orderDetailList);
            //2:总件数
            long totalNum = orderDetailList.stream().collect(
                    Collectors.summarizingInt(OrderDetail::getSkuNum)).getSum();
            result.put("totalNum", totalNum);

            //3:总金额
            BigDecimal totalAmount = new BigDecimal("0");
            for (OrderDetail orderDetail : orderDetailList) {
                BigDecimal orderPrice = orderDetail.getOrderPrice();
                totalAmount = totalAmount.add(orderPrice.multiply(new BigDecimal(orderDetail.getSkuNum())));
            }
            result.put("totalAmount", totalAmount);

            //4:交易号
            String tradeNo = UUID.randomUUID().toString().replaceAll("-", "");
            String userId = AuthContextHolder.getUserId(request);
            redisTemplate.opsForValue().set("tradeNo:" + userId, tradeNo);
            result.put("tradeNo", tradeNo);
        }

        return result;
    }

    //提交订单
    @PostMapping("/auth/submitOrder")
    public Result submitOrder(@RequestBody OrderInfo orderInfo, String tradeNo, HttpServletRequest request) {

        String userId = AuthContextHolder.getUserId(request);

        //1:校验交易号或订单号是否正确  防止二次提交  幂等性问题
        if (StringUtils.isEmpty(tradeNo)) {
            return Result.fail().message("非法操作");
        }
        Object o = redisTemplate.opsForValue().get("tradeNo:" + userId);
        //如果没有值 已经提交过了
        if (null == o) {
            return Result.fail().message("请误重复提交订单");
        } else if (!tradeNo.equals(o)) {
            return Result.fail().message("非法操作");
        }
        //交易号正确
        redisTemplate.delete("tradeNo:" + userId);
        //2:校验库存  （远程调用 仓库系统）
        //有库存  购买数量小于（剩余库存-锁定）  无库存 反之亦然
        List<OrderDetail> orderDetailList = orderInfo.getOrderDetailList();
        if (!CollectionUtils.isEmpty(orderDetailList)) {
            for (OrderDetail orderDetail : orderDetailList) {
                //校验库存
                boolean flag = orderInfoService.
                        hasStock(orderDetail.getSkuId(), orderDetail.getSkuNum());
                if (!flag) {
                    return Result.fail().message(orderDetail.getSkuName() + "[此商品已经售完]");
                }
            }
        }
        //3：保存订单表 订单详情表
        orderInfo.setUserId(Long.parseLong(userId));
        Long orderId = orderInfoService.submitOrder(orderInfo);
        return Result.ok(orderId);
    }

    //根据订单ID 查询订单对象
    @GetMapping("/getOrderInfo/{orderId}")
    public OrderInfo getOrderInfo(@PathVariable Long orderId){
        return orderInfoService.getOrderInfo(orderId);
    }

    //由仓库发出Http请求 要求折单
    @PostMapping("/orderSplit")
    public String orderSplit(Long orderId,String wareSkuMap){
        //查询仓库系统  拆单接口说明  具体代码
        //1:开始折单   拆单之后子订单集合
/*        List<OrderInfo> orderInfoList = orderInfoService.orderSplit(orderId,wareSkuMap);
        //2：折单后集合
        List<Map> listMap = orderInfoList.stream().map(orderInfo -> {
            return orderInfoService.initWareOrder(orderInfo);
        }).collect(Collectors.toList());*/
        List<Map> listMap =  orderInfoService.orderSplit1(orderId,wareSkuMap);
        //转成字符串
        return JSONObject.toJSONString(listMap);
    }


}
